package net.jalbum.filters;
import java.awt.event.ActionEvent;
import java.util.Vector;

import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;

import se.datadosen.jalbum.Msg;

public class CroppingControl extends BoxControl {
    
	private static final long serialVersionUID = -5810631993955435525L;
	protected CroppingFilterPlugin croppingFilterPlugin;
	protected JCheckBox keepRatio;
	protected JComboBox predefinedRatio;
	protected Vector<Double> predefinedRatioList;
        
        public static final double CROPSCALE = 0.9;
        private static final double ROUNDING_ERROR = 0.01;
        private static boolean muteListener = false;
        
        public static Boolean ratioLocked = true;
        public static int currentIndex = -1;
        
        private enum AspectRatio {

            GOLDENRATIO("5:8", 5/(double)8), TWOTHIRDS("2:3", 2/(double)3), THREEFOURTHS("3:4", 0.75), THIRTEENTOSEVENTEEN("13:17", 13/(double)17), FOURFIFTHS("4:5",0.8), SQUARE("1:1", 1), ONETOFOUR ("1:4", 0.25), ONETOTHREE ("1:3", 1/(double)3), ONEHALF("1:2", 0.5), NINETOSIXTEEN("9:16", 9/(double)16), NINETOTHIRTEEN("9:13", 9/(double)13), ELEVENTOFIFTEEN("11:15", 11/(double)15);
            private final String name; private final double ratio;
            private AspectRatio(String name, double ratio){this.name = name; this.ratio = ratio;}
        }
        
	public CroppingControl(){

	}

	public CroppingControl(CroppingFilterPlugin croppingFilterPlugin) {

		init(croppingFilterPlugin);
		addCroppingControl();
	}

	protected void init(CroppingFilterPlugin croppingFilterPlugin) {
		this.croppingFilterPlugin = croppingFilterPlugin;
		super.init(croppingFilterPlugin);
	}

	protected void addCroppingControl() {
		//Create UI-elements
		keepRatio = new JCheckBox(Msg.getString(this,"filters.cropping.keepRatio"), true);
		predefinedRatio = new JComboBox();

		predefinedRatioList= new Vector<Double>();
		initiatePredefinedRatios();
		
		//add ActionListeners
		keepRatio.addActionListener(this);
		predefinedRatio.addActionListener(this);

		//add elements to interface
		this.add("br",keepRatio);
		this.add("p", new JLabel(Msg.getString(this,"filters.cropping.predefinedRatio")));
		this.add("br", predefinedRatio);
                
                // check state of ratio lock (if deactivated before)
                keepRatio.setSelected(ratioLocked);
	}

	public void initiatePredefinedRatios() {
		predefinedRatio.removeAllItems();
		predefinedRatioList.removeAllElements();
		
		//create list of predefined ratios
		predefinedRatio.addItem("");
                for(AspectRatio a : AspectRatio.values()){
                    predefinedRatio.addItem(a.name);
                    predefinedRatioList.add(a.ratio);
                }
                // adding current image orientation to list:
                double imageRatio = (double)objectWidth/(double)objectHeight;
                predefinedRatio.insertItemAt(Msg.getString(this,"filters.cropping.imageRatio"),1);
                //predefinedRatio.setSelectedIndex(1);
                predefinedRatioList.add(0, imageRatio);
		//predefinedRatio.addItem("5:8 "+Msg.getString(this,"filters.cropping.goldenRatio"));
	}

	public void update(double x1, double y1, double boxWidth, double boxHeight) {
		super.update(x1, y1, boxWidth, boxHeight);
	}
        
        public void flipRatio(String type, int position){
            double imageRatio = (double)objectWidth/(double)objectHeight;
            double currentRatio = (double)boxWidth*imageRatio/(double)boxHeight;
	    double desiredRatio = (double)1 / currentRatio;	
            
            //System.out.println("flipping from: " + currentRatio + " to: " + desiredRatio);
            
            if (keepRatio.isSelected()) {
                double startX = X1;
                double startY = Y1;
                double oldWidth = (double)boxWidth;
                double oldHeight = (double)boxHeight;
                double newWidth = (desiredRatio / imageRatio) * (double)boxHeight;
                double newHeight = ((double)boxWidth / desiredRatio) * imageRatio;
                
                switch (position) {
                    case 2: // upperleft
                        if (type.equals("landscape")) {
                            startY = Y1 +(oldHeight - newHeight);
                            startX = X1;
                        } else if (type.equals("portrait")) {
                            startX = X1 + (oldWidth - newWidth);
                            startY = Y1;
                        }
                        break;
                    case 3: // upperright
                        if (type.equals("landscape")) {
                            startY = Y1 +(oldHeight - newHeight);
                        } else if (type.equals("portrait")) {
                            startY = Y1;
                        }
                        break;
                    case 5: // lowerleft
                        if (type.equals("landscape")) {
                            startX = X1;
                        } else if (type.equals("portrait")) {
                            startX = X1 + (oldWidth - newWidth);
                        }
                        break;
                }
                if (type.equals("portrait")) {
                    if (croppingFilterPlugin.croppingIsLandscape) {
                        croppingFilterPlugin.croppingIsLandscape = false;
                        boxWidth = (desiredRatio / imageRatio) * boxHeight;
                        croppingFilterPlugin.resizableBox.setRatio(boxWidth/boxHeight);
                        croppingFilterPlugin.updateObject(startX, startY, boxWidth, boxHeight);
                        croppingFilterPlugin.getResizableBox().adjustKeepRatio(true);
                        //aspectRatio.setSelectedIndex(0);
                    }
                } else if (type.equals("landscape")) {
                    if (!croppingFilterPlugin.croppingIsLandscape ) {
                        croppingFilterPlugin.croppingIsLandscape = true;
                        boxHeight = (boxWidth / desiredRatio) * imageRatio;
                        croppingFilterPlugin.resizableBox.setRatio(boxWidth/boxHeight);
                        croppingFilterPlugin.updateObject(startX, startY, boxWidth, boxHeight);
                        croppingFilterPlugin.getResizableBox().adjustKeepRatio(true);
                        //aspectRatio.setSelectedIndex(1);
                    }
                }
            }
        }
        
        public void checkExistingRatios(double setRatio){
            
            boolean exists = false;
            if (setRatio>1){
                setRatio = 1/setRatio;
            }
            for (int i = 0; i < predefinedRatioList.size(); i++) {
                // considering rounding errors
                if (Math.abs(predefinedRatioList.get(i)-setRatio)<=ROUNDING_ERROR){
                    muteListener = true;
                    predefinedRatio.setSelectedIndex(i+1);
                    exists = true;
                }
            }
            if(!exists){
                muteListener = true;
                predefinedRatio.setSelectedIndex(0);
            }
            muteListener = false;
        }
        
	public void actionPerformed(ActionEvent e) {
		//handle the input from various ui elements
		super.actionPerformed(e);
                
		if(e.getSource()==predefinedRatio){
                        if(!muteListener){
                            int index = predefinedRatio.getSelectedIndex();
                            if (index > 0) {
                                // -1 since empty String as first entry in the combobox
                                Double desiredRatio = predefinedRatioList.get(index - 1);
                                CroppingControl.currentIndex = index;
                                //predefinedRatio.setSelectedIndex(index-1);

                                croppingFilterPlugin.calcNewSize(desiredRatio, false, true);
                                croppingFilterPlugin.renderPreview();
                                croppingFilterPlugin.getResizableBox().adjustKeepRatio(keepRatio.isSelected());
                                
                                //newly Added
                                keepRatio.setSelected(true);
                                croppingFilterPlugin.getResizableBox().adjustKeepRatio(keepRatio.isSelected());
                                ratioLocked=true;
                            }
                        }
		}
                
		if(e.getSource()==keepRatio){
			//disable or enable everything that has an influence on the ratio
			croppingFilterPlugin.getResizableBox().adjustKeepRatio(keepRatio.isSelected());
                        // update orientation for flipping-tool:
                        croppingFilterPlugin.adjustCurrentCropOrientation();
                        
                        ratioLocked = keepRatio.isSelected();
                        
                        if(!ratioLocked){
                                CroppingControl.currentIndex = -1;
				predefinedRatio.setSelectedIndex(0);
			}
		}
	}
}
